﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using com.dz.common;
using System.Net;
namespace com.dz.components.background
{

    /* ***********************************************
    * 功能描述: 
    * 1、配置的要抓去的页面管理类
    * 2、根据配置的启动服务抓取书信息
    * ***********************************************/
    public class BookSiteManager
    {

        /// <summary>
        /// 页面超时时间
        /// </summary>
        const int c_TIME_OUT = 60000;


        /// <summary>
        /// 读取页面内容
        /// </summary>
        /// <param name="i_url"></param>
        /// <param name="i_encoding"></param>
        /// <returns></returns>
        public static string ReadUrl(string i_url, Encoding i_encoding)
        {
            System.Threading.Thread.Sleep(500);
            Encoding t_encoding = null;
            string t_html = string.Empty;
            try
            {
                using (MemoryStream t_memory_stream = new MemoryStream())
                {
                    ReadPageCodeToStream(i_url, t_memory_stream, delegate(HttpWebResponse t_response)
                    {
                        t_encoding = i_encoding ?? GetEncoding(t_response);
                    });

                    t_memory_stream.Position = 0;//内存流复位以便于重新读取

                    using (StreamReader t_reader = new StreamReader(t_memory_stream, t_encoding))
                    {
                        t_html = t_reader.ReadToEnd();
                    }
                }
                if (!string.IsNullOrEmpty(t_html))
                {
                    t_html = t_html.Replace("\r", "").Replace("\n", "").Replace("\r\n", "");
                }
                return t_html;
            }
            catch (Exception ex)
            {

                LogHelper.Error("获取页面内容失败" + ex.ToString() + ",url=" + i_url);
                ex = null;
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取页面编码
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private static Encoding GetEncoding(HttpWebResponse response)
        {

            Encoding t_encoding = Encoding.Default;
            if (response.CharacterSet != null)
            {
                try
                {
                    t_encoding = Encoding.GetEncoding(response.CharacterSet);
                }
                catch (ArgumentException ex)
                {
                    LogHelper.Error("获取页面编码失败" + ex.ToString());
                }
            }
            return t_encoding;
        }

        /// <summary>
        /// 读取页面内容到数据流
        /// </summary>
        /// <param name="i_url"></param>
        /// <param name="i_stream"></param>
        /// <param name="ResponseCallback"></param>
        private static void ReadPageCodeToStream(string i_url, Stream i_stream, Action<HttpWebResponse> ResponseCallback)
        {
            HttpWebRequest t_request = (HttpWebRequest)WebRequest.Create(i_url);
            t_request.Timeout = c_TIME_OUT;
            t_request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5 (.NET CLR";
            t_request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            t_request.Headers["Accept-Language"] = "en-us,en;q=0.5";
            t_request.Headers["Accept-Charset"] = "ISO-8859-1,utf-8;q=0.7,*;q=0.7";

            using (HttpWebResponse t_response = (HttpWebResponse)t_request.GetResponse())
            {
                if (ResponseCallback != null)
                {
                    ResponseCallback(t_response);
                }

                Stream t_stream = t_response.GetResponseStream();

                byte[] t_buffer = new byte[100000];
                int t_count = 0;
                while ((t_count = t_stream.Read(t_buffer, 0, t_buffer.Length)) != 0)
                {
                    i_stream.Write(t_buffer, 0, t_count);
                }
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="i_img_url"></param>
        /// <param name="i_file_name"></param>
        public static void DownLoadImage(string i_img_url, long i_book_id)
        {
            WebClient t_web_client = new WebClient();

            string t_file_path = AppConfig.BookImgRoot;

            if (!Directory.Exists(t_file_path))
            {
                Directory.CreateDirectory(t_file_path);
            }
            string t_file_name = Path.Combine(t_file_path, string.Format("{0}.jpg",i_book_id));

            try
            {
                if (!File.Exists(t_file_name))
                {
                    LogHelper.Info(string.Format("下载了封面:{0}", t_file_name));
                    t_web_client.DownloadFile(i_img_url, t_file_name);
                }

            }
            catch (Exception ex)
            {
                DataManager t_data_mgr = new DataManager();
                t_data_mgr.UpdateBookExistImage(i_book_id, 0);
                LogHelper.Error("下载文件失败" + ex.ToString());
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="i_img_url"></param>
        /// <param name="i_file_name"></param>
        public static void DownLoadFile(string i_url, string i_file_name)
        {

           try
           {
                Uri u = new Uri(i_url);
                HttpWebRequest mRequest = (HttpWebRequest)WebRequest.Create(u);
                mRequest.Method = "GET";
                mRequest.ContentType = "Application/octet-stream";
                HttpWebResponse wr = (HttpWebResponse)mRequest.GetResponse();
               
                
                Stream sIn = wr.GetResponseStream();
                FileStream fs = new FileStream(i_file_name, FileMode.Create, FileAccess.Write);
                long length = wr.ContentLength;
                int i = 0;    
                long j=0;

                byte[] buffer = new byte[1024];
                while ((i = sIn.Read(buffer, 0, buffer.Length)) > 0)
                {
                     j+=i;     
                     fs.Write(buffer, 0,i);

                
                }

                sIn.Close();
                wr.Close();

                fs.Close();

           }
           catch {  }




        }

        /// <summary>
        /// http POST请求url
        /// </summary>
        /// <param name="apiUrl"></param>
        /// <param name="method_name"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string GetHttpWebResponse(string url, string postData)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.Length;
            request.Timeout = 20000;

            HttpWebResponse response = null;

            try
            {
                StreamWriter swRequestWriter = new StreamWriter(request.GetRequestStream());
                swRequestWriter.Write(postData);

                if (swRequestWriter != null)
                    swRequestWriter.Close();

                response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
            finally
            {
                if (response != null)
                    response.Close();
            }
        }

    }
}
